#include <iostream>
#include <sys/socket.h>
#include <poll.h>
#include <netinet/in.h>
#include <unistd.h>
#include <sys/select.h>
#include <vector>
#include <cstring>

#define MAX_CLIENTS 10
#define BUFFER_SIZE 1024

int main(int argc, char* argv[]) 
{
    if(argc != 2)
    {
        std::cerr << "Usage: " << argv[0] << std::endl;
    }
    uint16_t port = std::stoi(argv[1]);

    // 1. 创建TCP socket
    int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0){
        perror("socket failed");
    }

    // 设置socket选项（允许地址重用）
    int opt = 1;
    if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))) {
        perror("setsockopt");
    }
    
    // 2. 填充信息
    struct sockaddr_in address;
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(port);

    // 3. 绑定socket到端口
    if (bind(sockfd, (struct sockaddr *)&address, sizeof(address)) < 0) {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }

    // 4. 开始监听
    if (listen(sockfd, 3) < 0) {
        perror("listen");
        exit(EXIT_FAILURE);
    }


    int addrlen = sizeof(address), new_socket;
    char buffer[BUFFER_SIZE] = {0};

    std::vector<pollfd> poll_fds;  // 动态管理pollfd结构体数组
    poll_fds.push_back({sockfd, POLLIN, 0});  // 监听服务器socket
    while (true) {
        // 调用poll，阻塞等待事件
        int activity = poll(poll_fds.data(), poll_fds.size(), -1);
        if (activity < 0) {
            perror("poll error");
            exit(EXIT_FAILURE);
        }

        // 遍历所有文件描述符处理事件
        for (size_t i = 0; i < poll_fds.size(); ++i) {
            if (poll_fds[i].revents & POLLIN) {
                if (poll_fds[i].fd == sockfd) {
                    // 处理新连接
                    if ((new_socket = accept(sockfd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
                        perror("accept");
                        continue;
                    }
                    std::cout << "New client connected, fd: " << new_socket << std::endl;
                    poll_fds.push_back({new_socket, POLLIN, 0});  // 添加新客户端到监控列表
                } else {
                    // 处理客户端数据
                    char buffer[BUFFER_SIZE];
                    int valread = read(poll_fds[i].fd, buffer, BUFFER_SIZE);
                    if (valread == 0) {  // 客户端断开连接
                        std::cout << "Client disconnected, fd: " << poll_fds[i].fd << std::endl;
                        close(poll_fds[i].fd);
                        poll_fds.erase(poll_fds.begin() + i);  // 从监控列表移除
                        --i;  // 调整索引（因删除元素）
                    } else {  // 回显数据
                        buffer[valread] = '\0';
                        std::cout << "Received: " << buffer << std::endl;
                        send(poll_fds[i].fd, buffer, valread, 0);
                    }
                }
            }
        }
    }

    return 0;
}